<template>
  <el-dialog :title="'等级价格-【'+levelItem.name+'】'"
             :before-close="close"
             :visible.sync="visible">
    <div class="app-container">

      <div class="filter-container">
        <el-button-group>
          <el-button class="filter-item"
                     size="mini"
                     type="primary"
                     icon="el-icon-edit"
                     @click="handleCreate">添加
          </el-button>
          <el-button class="filter-item"
                     size="mini"
                     type="danger"
                     icon="el-icon-delete"
                     @click="handleDelete">删除
          </el-button>
        </el-button-group>
      </div>
      <el-table :key="tableKey"
                :data="list"
                border
                fit
                highlight-current-row
                style="width: 100%;"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         width="55"
                         align="center"></el-table-column>
        <el-table-column label="时限"
                         align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.timeType | timeTypeFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售价"
                         align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原始售价"
                         align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.priceOriginal }}</span>
          </template>
        </el-table-column>
        <el-table-column label="显示隐藏"
                         align="center">
          <template slot-scope="scope">
            <el-switch :active-value="1"
                       :inactive-value="0"
                       v-model="scope.row.isShow"
                       @change="isShowChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column :label="$t('table.actions')"
                         class-name="small-padding"
                         fixed="right"
                         min-width="120">
          <template slot-scope="scope">
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="handleUpdate(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.page"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>

      <!--添加编辑框-->
      <el-dialog :title="dialogType==='edit'?'编辑':'新增'" append-to-body
                 :visible.sync="dialogFormVisible">
        <el-form ref="dataForm"
                 :model="config"
                 label-width="100px"
                 label-position="right"
                 style="width: 100%; margin-left: 50px;">
          <el-form-item label="显示隐藏"
                        prop="isShow"
                        :rules="[{ required: true, message: '请选择显示隐藏', trigger: 'change' }]">
            <el-switch v-model="config.isShow"
                       :active-value="1"
                       :inactive-value="0">
            </el-switch>
          </el-form-item>

          <el-form-item label="时限"
                        prop="timeType"
                        :rules="[{ required: true, message: '请选择等级时限', trigger: 'change' }]">
            <el-select v-model="config.timeType" placeholder="请选择" filterable clearable class="filter-item">
              <el-option v-for="item in timeTypeOptions" :key="item.key" :label="item.text" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="售价"
                        prop="price"
                        :rules="[{ required: true, message: '请填写等级', trigger: 'blur'}]">
            <el-input v-model="config.price"
                      type="number"
                      style="width: 60%"></el-input>
          </el-form-item>
          <el-form-item label="原始售价"
                        prop="priceOriginal"
                        :rules="[{ required: true, message: '请填写服务名称', trigger: 'blur' }]">
            <el-input v-model="config.priceOriginal"
                      style="width: 60%"></el-input>
          </el-form-item>


        </el-form>
        <div style="text-align:right;">
          <el-button type="danger"
                     @click="dialogFormVisible=false">取消
          </el-button>
          <el-button type="primary"
                     @click="confirm">确定
          </el-button>
        </div>
      </el-dialog>

    </div>
  </el-dialog>
</template>

<script>
import {getListShopLevelPrice, editSubmitLevelPrice, deleteShopLevelPrice} from '@/api/shopLevel'
import waves from '@/directive/waves' // Waves directive
import {parseTime, renderTime, moneyFormat} from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const timeTypeOptions = [
  {key: 1, text: '包月'},
  {key: 2, text: '包季'},
  {key: 3, text: '包年'},
  // {key: 4, text: '连续包月'},
  // {key: 5, text: '连续包季'},
  // {key: 6, text: '连续包年'},
  {key: 7, text: '15天'},
]
const timeTypeKeyValue = timeTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.text
  return acc
}, {})
export default {
  props: {
    levelItem: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    },
  },
  name: 'shopService',
  components: {Pagination},
  directives: {waves},
  filters: {
    timeTypeFilter(timeType) {
      return timeTypeKeyValue[timeType]
    },
  },

  data() {
    return {
      timeTypeOptions,
      currentLevel: {},
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20,
      },
      config: {},
      dialogFormVisible: false,
      dialogType: '',
      multipleSelection: [],
      locationActiveName: 'first',
    }
  },
  created() {
    this.getList()
  },
  methods: {
    close() {
      this.$emit('update:visible', false)

    },
    getList() {
      this.listLoading = true
      let queryParams = this.listQuery
      queryParams.levelId = this.levelItem.id
      getListShopLevelPrice(queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },

    handleCreate() {
      this.dialogType = 'add'
      this.dialogFormVisible = true
      this.config = {status: 1}
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.dialogType = 'edit'
      this.dialogFormVisible = true
      this.config = Object.assign({}, row) // copy obj
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let formData = Object.assign({}, this.config)
          formData.addTime = null
          formData.updTime = null
          if (!formData.levelId) {
            formData.levelId = this.levelItem.id
          }

          editSubmitLevelPrice(formData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleDelete() {
      const delVals = this.multipleSelection;
      if (!delVals || delVals.length <= 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 2000
        })
        return;
      }
      this.$confirm('您确定要删除这些记录?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let values = [];
        delVals.forEach(val => {
          values.push(val.id);
        })
        deleteShopLevelPrice(values.join(',')).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
        .catch(err => {
          console.error(err)
        })


    },

    isShowChange(row) {
      let formData = {
        isShow: row.isShow,
        id: row.id
      }
      editSubmitLevelPrice(formData).then(() => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },


  }
}
</script>
